package chapter2;

import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author caiya
 * @date 2020/3/16 20:38
 */
@Slf4j
public class UnsafeTest {
    private volatile long state;
    private static Unsafe unSafe;
    private static long stateOffset;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);

            unSafe = (Unsafe) field.get("theUnsafe");
            stateOffset = unSafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        /**
         * Unsafe 类：
         * CAS 操作的提供类，位于rt.jar包中，提供硬件级别的原子操作
         */
        UnsafeTest unsafeTest = new UnsafeTest();
        boolean swapLong = unSafe.compareAndSwapLong(unsafeTest, stateOffset, 0, 1);
        log.debug("swapLong: {}", swapLong);
    }
}
